1 module hip.filesystem.systems.browser;
2 
3 version(WebAssembly):
4 
5 /**
6 *   directories.json is an auto generated file which saves a list of all directories for your game assets.
7 *   With that, it is possible to reproduce some commands such as exists or isDir.
8 *   It is also possible to get the file size upfront.
9 */
10 immutable string directories = import("directories.json");
11 
12 import hip.api.filesystem.hipfs;
13 import hip.filesystem.hipfs;
14 
15 version(WebAssembly):
16 import hip.wasm;
17 
18 
19 private extern(C) void WasmRead(JSStringType str,
20     JSDelegateType!(void delegate(ubyte[])) onSuccess, 
21     JSDelegateType!(void delegate(string)) onError
22 );
23 
24 class HipBrowserFileSystemInteraction : IHipFileSystemInteraction
25 {
26     import hip.data.json;
27     JSONValue dirsJson;
28     this()
29     {
30         dirsJson = parseJSON(directories);
31         if(dirsJson.hasErrorOccurred)
32         {
33             import hip.error.handler;
34             ErrorHandler.assertExit(false, "Could not parse directories.json, required for BrowserFS. Got `"~directories~"`\n\t Error: "~dirsJson.error);
35         }
36     }
37     
38     bool read(string path, void delegate(ubyte[] data) onSuccess, void delegate(string err = "Corrupted File") onError)
39     {
40         JSONValue dummy = void;
41         import hip.console.log;
42         if(!getFromPath(path, dummy))
43         {
44             hiplog("Browser could not read ", path);
45             return false;
46         }
47         hiplog("Browser read start on ", path);
48 
49         WasmRead(JSString(path).tupleof, sendJSDelegate!((ubyte[] wasmBin)
50         {
51             onSuccess(wasmBin);
52         }).tupleof, sendJSDelegate!(onError).tupleof);
53         
54         return true;
55     }
56     bool write(string path, void[] data){return false;}
57 
58     private bool getFromPath(string path, out JSONValue output)
59     {
60         import hip.util.path:pathSplitterRange, normalizePath;
61         output = dirsJson;
62         import hip.console.log;
63         hiplog("Testing ", path.normalizePath);
64         foreach(p; pathSplitterRange(path.normalizePath))
65         {
66             JSONValue* currAddr = p in output;
67             if(currAddr is null)
68                 return false;
69             output = *currAddr;
70         }
71         return true;
72     }
73     bool exists(string path)
74     {
75         JSONValue dummy = void;
76         return getFromPath(path, dummy);
77     }
78     bool remove(string path){return false;}
79 
80     bool isDir(string path)
81     {
82         JSONValue temp = void;
83         if(!getFromPath(path, temp))
84             return false;
85         return temp.type == JSONType.object;
86     }
87 
88     ~this()
89     {
90         dirsJson.dispose();       
91     }
92 
93 }